package org.sherlock.downloader;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;

public class DownloadsNotifier extends Observable implements Observer {

	private static final long DEFAULT_PERIOD = 1000;
	
	private ArrayList<Download> downloadsUpdated;
	private Timer timer;	
	
	public DownloadsNotifier() {
		this(DEFAULT_PERIOD);
	}
	
	public DownloadsNotifier(long period) {
		this.downloadsUpdated = new ArrayList<Download>();
				
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				update();
			}				
		}, 0, period);
	}

	public void addDownload(Download download) {
		download.addObserver(this);
	}

	public void update() {
		if (!downloadsUpdated.isEmpty()) {
			setChanged();
			notifyObservers(downloadsUpdated.clone());
			downloadsUpdated.clear();
		}
	}
	
	@Override
	public void update(Observable arg0, Object arg1) {
		if (arg0 instanceof Download) {
			Download download = (Download) arg0;
			if (!downloadsUpdated.contains(download)) {
				downloadsUpdated.add(download);
			}
		}
	}
}
